package com.sz.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    private long ttl = 900000; // 15分钟


    //新建一个签证，返回token
    public String createJwt(String pkUserId, String ukPhone, String subject, String roles) {
        // 获取当前时间
        long time = System.currentTimeMillis();
        // 签发时间
        Date now = new Date(time);
        // 过期时间
        Date exp = new Date(time + ttl);

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(pkUserId)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(exp)
                .signWith(SignatureAlgorithm.HS256, ukPhone)
                .claim("roles", roles);

        return jwtBuilder.compact();
    }

    // 解析token
    public Claims parseJwt(String ukPhone, String token) {
        return Jwts.parser()
                .setSigningKey(ukPhone)
                .parseClaimsJws(token)
                .getBody();
    }
}
